﻿

#region Usings
using System;
using System.Text;
using Jenvin.Library.Utils.Encryption;
#endregion

namespace Jenvin.Library.Utils.Encryption
{
    /// <summary>
    /// Vernam encryption
    /// </summary>
    public class VernamEncryption:ISymEncryption
    {
        /// <summary>
        /// 加密Key
        /// Vernam 算法的加密Key 必须和加密的字串一样
        /// </summary>
        public string Key
        {
            get;
            set;
        }
        public string IV
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Input"></param>
        /// <param name="Key"></param>
        /// <returns></returns>
        public  string Encrypt(string input)
        {
            if (string.IsNullOrEmpty(Key))
            {
                throw new InvalidOperationException("The key don't set.");
            }
            return Process(input, Key);
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Input"></param>
        /// <param name="Key"></param>
        /// <returns></returns>
        public string Decrypt(string input)
        {
            if (string.IsNullOrEmpty(Key))
            {
                throw new InvalidOperationException("The key don't set.");
            }
            return Process(input, Key);
        }

        private static string Process(string input, string key)
        {
            if (input.Length != key.Length)
            {
                throw new ArgumentException("Key is not the same length as the input string");
            }
            ASCIIEncoding Encoding = new ASCIIEncoding();
            byte[] InputArray = Encoding.GetBytes(input);
            byte[] KeyArray = Encoding.GetBytes(key);
            byte[] OutputArray = new byte[InputArray.Length];
            for (int x = 0; x < InputArray.Length; ++x)
            {
                OutputArray[x] = (byte)(InputArray[x] ^ key[x]);
            }
            return Encoding.GetString(OutputArray);
        }

        public void Encrypt(System.IO.Stream inputStream, System.IO.Stream outputStream)
        {
            throw new NotImplementedException();
        }

        public void Decrypt(System.IO.Stream inputStream, System.IO.Stream outputStream)
        {
            throw new NotImplementedException();
        }

    }
}